<template>
  <div class="comp-sale-search-product">
    <!-- 输入框 -->
    <n-input
      clearable
      :placeholder="$attrs.placeholder"
      v-bind:value="$props.value"
      @input="$emit('update:value', $event)"
      @keyup.enter="handleSearch"
    />
    <!-- 选择框 -->
    <div class="choose-table" v-if="showTable">
      <n-grid x-gap="12" :cols="24" class="flex items-center">
        <n-gi :span="8">
          <n-select
            clearable
            value-field="id"
            label-field="name"
            :options="categoriesList"
            v-model:value="searchForm.categoryId"
            placeholder="请选择产品类别"
            @update:value="handleSearch"
          />
        </n-gi>
        <n-gi :span="8">
          <n-select
            clearable
            value-field="id"
            label-field="name"
            :options="brandsList"
            v-model:value="searchForm.brandId"
            placeholder="请选择品牌"
            @update:value="handleSearch"
          />
        </n-gi>
        <n-gi :span="6">
          <n-checkbox
            v-model:checked="searchForm.inStock"
            :checked-value="'1'"
            :unchecked-value="'0'"
            @update:checked="handleSearch"
          >
            只看有库存
          </n-checkbox>
        </n-gi>
        <n-gi :span="2" class="text-right">
          <n-button quaternary circle @click.stop="handleClickClose">
            <template #icon>
              <n-icon size="20">
                <close />
              </n-icon>
            </template>
          </n-button>
        </n-gi>
      </n-grid>
      <div class="mt-[8px] content-wrapper">
        <n-tabs placement="left" type="line">
          <n-tab-pane name="inventoryList" tab="商品库存">
            <n-scrollbar style="height: 50vh">
              <n-spin :show="variantListLoading">
                <template v-if="variantListInfo.dataList.length">
                  <!-- 添加商品库存表头 -->
                  <div class="search-result-header">
                    <div class="flex-1">
                      <span>商品</span>
                    </div>
                    <div class="flex-1 flex justify-between items-center">
                      <span>可用库存</span>
                      <span>价格</span>
                    </div>
                  </div>
                  <div
                    v-for="item in variantListInfo.dataList"
                    :key="item.id"
                    class="search-result-item"
                    @click.stop="handlePickVariant(item)"
                  >
                    <div class="flex-1">
                      <span>{{ item.name }}</span>
                    </div>
                    <div class="flex-1 flex justify-between items-center">
                      <span>{{ item.qtyAvailable }}</span>
                      <span class="font-bold">{{
                        currencyFormat(item.soldPrice)
                      }}</span>
                    </div>
                  </div>
                </template>
                <n-empty class="mt-20" v-else />
              </n-spin>
            </n-scrollbar>
            <div class="mt-2 flex justify-end">
              <n-pagination
                :page="variantListInfo.pageNo"
                :page-size="variantListInfo.pageSize"
                :item-count="variantListInfo.total"
                @update:page="handleVariantPageChange"
              />
            </div>
          </n-tab-pane>
          <n-tab-pane v-if="showImeiTag" name="snsList" tab="序列号">
            <n-scrollbar style="height: 50vh">
              <n-spin :show="snsListLoading">
                <template v-if="snsListInfo.dataList.length">
                  <!-- 添加序列号表头 -->
                  <div class="search-result-header">
                    <div class="flex-1">
                      <span>序列号</span>
                    </div>
                    <div class="flex-1 flex justify-between items-center">
                      <span>商品</span>
                      <span></span>
                    </div>
                  </div>
                  <div
                    v-for="item in snsListInfo.dataList"
                    :key="item.snId"
                    class="search-result-item"
                    @click.stop="handlePickSn(item)"
                  >
                    <div class="flex-1">
                      <span>{{ item.snName }}</span>
                    </div>
                    <div class="flex-1 flex justify-between items-center">
                      <span>{{ item.variantName }}</span>
                    </div>
                  </div>
                </template>
                <n-empty class="mt-20" v-else />
              </n-spin>
            </n-scrollbar>
            <div class="mt-2 flex justify-end">
              <n-pagination
                :page="snsListInfo.pageNo"
                :page-size="snsListInfo.pageSize"
                :item-count="snsListInfo.total"
                @update:page="handleSnsPageChange"
              />
            </div>
          </n-tab-pane>
        </n-tabs>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { reactive, ref } from "vue";
import { debounce, get } from "lodash-es";
import { Close } from "@vicons/ionicons5";
import { getBrands } from "@/api/product/brand.api";
import { getCategories } from "@/api/product/category.api";
import { searchVariant, searchSnsList } from "@/api/sales/sales.api";
import { SalesSearchSnVO, SalesSearchVariantVO, SNVO } from "@/types/model/sales/vos/sales.vo";
import { Category } from "@/types/model/product/vos/category.vo";
import { currencyFormat } from "@/common/utils/currencyFormatter/index.ts";
import { ISaleSearchProductProps } from "./props";

const $emit = defineEmits(["update:value", "close", "pickVariant", "pickSn"]);
const props = withDefaults(defineProps<ISaleSearchProductProps>(), {
  showImeiTag: false,
});

const isInit = ref<boolean>(false);
const categoriesList = ref<Category[]>([]);
const brandsList = ref<any[]>([]);

const showTable = ref<boolean>(false);
const variantListLoading = ref<boolean>(false);
const snsListLoading = ref<boolean>(false);

const searchForm = reactive({
  categoryId: undefined,
  brandId: undefined,
  inStock: "0",
});

const variantListInfo = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
  dataList: [] as SalesSearchVariantVO[],
});

const snsListInfo = reactive({
  pageNo: 1,
  pageSize: 10,
  total: 0,
  dataList: [] as SalesSearchSnVO[],
});

const handlePickVariant = debounce((payload: SalesSearchVariantVO) => {
  $emit("pickVariant", payload);
  showTable.value = false;
}, 200);

const handlePickSn = debounce((payload: SalesSearchSnVO) => {
  $emit("pickSn", payload);
  showTable.value = false;
}, 200);

const init = async () => {
  if (isInit.value) {
    return;
  }
  await getCategoriesList();
  await getBrandsList();
  isInit.value = true;
};

const getCategoriesList = async () => {
  try {
    const result = await getCategories({
      page: 1,
      pageSize: 1000,
    });
    categoriesList.value = get(result, "result.records") || [];
  } catch (err) {
    console.log(err);
  }
};

const getBrandsList = async () => {
  try {
    const result = await getBrands({
      page: 1,
      pageSize: 1000,
    });
    brandsList.value = get(result, "result.records") || [];
  } catch (err) {
    console.log(err);
  }
};

const handleClickClose = () => {
  showTable.value = false;
  $emit("update:value", "");
  $emit("close");
};

const handleSearch = debounce(async function () {
  init();
  showTable.value = true;
  handlerSearchVariant();
  if (props.showImeiTag) {
    handlerSearchSns();
  }
});

const handleVariantPageChange = (page: number) => {
  variantListInfo.pageNo = page;
  handlerSearchVariant();
};

const handleSnsPageChange = (page: number) => {
  snsListInfo.pageNo = page;
  handlerSearchSns();
};

const handlerSearchVariant = async () => {
  const params = {
    categoryId: searchForm.categoryId,
    brandId: searchForm.brandId,
    name: props.value,
    inStock: searchForm.inStock,
    pageNo: variantListInfo.pageNo,
    pageSize: variantListInfo.pageSize,
  };
  variantListLoading.value = true;
  try {
    const res = await searchVariant(params);
    variantListInfo.pageNo = get(res, "result.current") || 1;
    variantListInfo.pageSize = get(res, "result.size") || 10;
    variantListInfo.total = get(res, "result.total") || 0;
    variantListInfo.dataList = get(res, "result.records") || [];
  } finally {
    variantListLoading.value = false;
  }
};

const handlerSearchSns = async () => {
  const params = {
    categoryId: searchForm.categoryId,
    brandId: searchForm.brandId,
    statusList: "available",
    snName: props.value,
    pageNo: snsListInfo.pageNo,
    pageSize: snsListInfo.pageSize,
  };
  snsListLoading.value = true;
  try {
    const res = await searchSnsList(params);
    snsListInfo.pageNo = get(res, "result.current") || 1;
    snsListInfo.pageSize = get(res, "result.size") || 10;
    snsListInfo.total = get(res, "result.total") || 0;
    snsListInfo.dataList = get(res, "result.records") || [];
  } finally {
    snsListLoading.value = false;
  }
};
</script>
<style lang="scss" scoped>
@import "./index.scss";
</style>
